package com.cyou.nad.tag.table;

import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.Tag;

import com.cyou.nad.datastore.DBHeader;
import com.cyou.nad.datastore.DataList;



/**
 * table 迭代标签的 行标签，在table 标签内部  包含 col 才能使用
 * @author lzm 
 */
public class RowTag extends BodyTagSupport {

	public static final String DATA_LIST_DATA = "DATA_LIST_DATA";
	public static final String DATA_LIST_CURRENT_ROW = "DATALIST_CURRENTROW";
	/**
	 * 
	 */
	private static final long serialVersionUID = 1304598607096181795L;

	@Override
	public int doAfterBody() throws JspException {
		if (currentRow < dataList.rowCount() - 1) {
			currentRow++;
			setAttr();
			return EVAL_BODY_AGAIN;
		} else
			return SKIP_BODY;
	}

	@Override
	public int doEndTag() throws JspException {
		pageContext.removeAttribute(DATA_LIST_CURRENT_ROW);
		pageContext.removeAttribute(DATA_LIST_DATA);
		
		List<DBHeader> header = dataList.getHeaders();
		for (DBHeader dbHeader : header) {
			pageContext.removeAttribute(dbHeader.getColDBName());
		}
		return EVAL_PAGE;
	}

	@Override
	public int doStartTag() throws JspException {
		Tag tag = getParent();
		if (tag == null || !(tag instanceof TableTag))
			throw new JspException("RowTag must in TableTag ");
		TableTag tabletag = (TableTag) tag;
		currentRow = 0;
		dataList = ((TableTag) tabletag).getDataList();
		setAttr();
		if (dataList == null || dataList.rowCount() <= 0)
			return SKIP_BODY;
		return EVAL_BODY_INCLUDE;
	}

	private void setAttr() {
		pageContext.setAttribute(DATA_LIST_CURRENT_ROW, currentRow, PageContext.PAGE_SCOPE);
		pageContext.setAttribute(DATA_LIST_DATA, dataList, PageContext.PAGE_SCOPE);
		List<DBHeader> header = dataList.getHeaders();
		int i=0;
		
		//把每一行数据放到pageContext中
		for (DBHeader dbHeader : header) {
			pageContext.setAttribute(dbHeader.getColDBName(), dataList.getObject(currentRow, i++));
		}
	}

	protected DataList getDatastoreObj() {
		return dataList;
	}

	public int getCurrRow() {
		return currentRow;
	}

	private DataList dataList;
	private int currentRow;
}
